<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="供应商" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单时间">
        <el-date-picker
          v-model="daterangePurchaseDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="编号" prop="purchaseSn">
        <el-input
          v-model="queryParams.purchaseSn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合计总金额" prop="purchaseTotal">
        <NumberBetween v-model="rangeArray" ></NumberBetween>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['webshop:GoodsPurchase:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"

          icon="el-icon-plus"
          size="mini"
          @click="handleAddAll"
          v-hasPermi="['webshop:GoodsPurchase:add']"
        >新增(all)</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['webshop:GoodsPurchase:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GoodsPurchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"    >
<!--        <template slot-scope="scope">-->
<!--          <el-checkbox v-model="scope.row.checked" :disabled="scope.row.purchaseState != 0" @change="handleSelectionChange(scope.row)"></el-checkbox>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column label="订单主键" align="center" prop="purchaseId" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="订单时间" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="purchaseSn" />
      <el-table-column label="说明" align="center" prop="purchaseInfo" />
      <el-table-column label="合计总金额" align="center" prop="purchaseTotal" >
        <template slot-scope="scope">
          <span>{{ '￥' + scope.row.purchaseTotal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="purchaseState" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.purchaseState == 0" type="success">草稿</el-tag>
          <el-tag v-if="scope.row.purchaseState == 1" type="warning">申请</el-tag>
          <el-tag v-if="scope.row.purchaseState == 2" type="primary">审批</el-tag>
          <el-tag v-if="scope.row.purchaseState == 3" type="danger">异常</el-tag>
          <el-tag v-if="scope.row.purchaseState == 4" type="info">结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="明细" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="showDetail(scope.row)"

          >查看明细</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.purchaseState == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateAndGoodsSku(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.purchaseState == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商" prop="supplierName">
          <el-col :span="18">
            <el-input v-model="form.supplierName"  :disabled="true" clearable  placeholder="请选择供应商" />
          </el-col>
          <el-col :span="6">
            <el-button style="margin-left: 10px;" type="success" @click="openSupplierPage" >选择供应商</el-button>
          </el-col>
        </el-form-item>
<!--        <el-form-item label="订单时间" prop="purchaseDate">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.purchaseDate"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择订单时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="编号" prop="purchaseSn">
          <el-input v-model="form.purchaseSn" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="说明" prop="purchaseInfo">
          <el-input v-model="form.purchaseInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="合计总金额" prop="purchaseTotal">-->
<!--          <el-input v-model="form.purchaseTotal" placeholder="请输入合计总金额" />-->
<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="titleAll" :visible.sync="openAll" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="供应商" prop="supplierName">
          <el-col :span="20">
            <el-input v-model="form.supplierName"  :disabled="true"  placeholder="请选择供应商" />
          </el-col>
          <el-col :span="4">
            <el-button style="margin-left: 10px;" type="success" @click="openSupplierPage" >选择供应商</el-button>
          </el-col>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="purchaseSn">
              <el-input v-model="form.purchaseSn" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合计总金额" prop="purchaseTotal">
              <el-input v-model="form.purchaseTotal"  :readonly="true" placeholder="请输入合计总金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="说明" prop="purchaseInfo">
          <el-input v-model="form.purchaseInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item >
          <el-button type="warning" @click="openGoodsSkuPage">选择商品</el-button>
        </el-form-item>

        <el-table  :data="goodsSkuInfoList"  v-if="goodsSkuInfoList.length>0" >
          <el-table-column label="细分主键" align="center" prop="skuId" />
          <el-table-column label="商品" width="100px" align="center" prop="goodsName" />
          <el-table-column label="商品标题" width="700px" align="center" prop="skuTitle" />
          <el-table-column label="原价" align="center" prop="purchaseDetailPrice" />
<!--          <el-table-column label="当前价格" align="center" prop="skuNowPrice" />-->
          <el-table-column label="数量" align="center"  >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.purchaseDetailCount" :min="1"  size="mini"  />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteGoodsSku(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAll">确 定</el-button>
        <el-button @click="openAll=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="titleDetail" :visible.sync="openDetail" width="1500px" append-to-body>

      <el-table v-loading="loading" :data="GoodsPurchaseDetailList" >
        <el-table-column label="序号" type="index" width="50px" align="center" />
        <el-table-column label="采购订单明细主键" align="center" prop="purchaseDetailId" />
        <el-table-column label="细分商品" width="800px" align="center" prop="skuTitle" />
        <el-table-column label="数量" align="center" prop="purchaseDetailCount" />
        <el-table-column label="价格" align="center" prop="purchaseDetailPrice" />
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
    </el-dialog>


    <SupplierModal ref="SupplierModal"  v-if="openSelectSupplier"
      @selectSupplier = "selectSupplier"
    ></SupplierModal>



    <GoodsSkuModal ref="GoodsSkuModal"  v-if="openSelectSku"
      @selectSkuList = "selectSkuList"
    ></GoodsSkuModal>


  </div>
</template>

<script>
import { listGoodsPurchase, getGoodsPurchase, delGoodsPurchase, addGoodsPurchase, updateGoodsPurchase } from "@/api/webshop/GoodsPurchase";
import { getGoodsSkuInfoByPurchaseId } from "@/api/webshop/GoodsPurchaseDetail"
import SupplierModal from "./SupplierModal.vue"
import GoodsSkuModal from "./GoodsSkuModal.vue"
import NumberBetween from "@/components/SmallComp/NumberBetween.vue"

export default {
  name: "GoodsPurchase",
  components: {
    SupplierModal, GoodsSkuModal , NumberBetween
  },
  data() {
    return {

      detailCount:[],

      openSelectSupplier:false,
      openSelectSku : false,

      goodsSkuInfoList:[],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      GoodsPurchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      openAll :false,
      titleAll: "",

      titleDetail: "",
      openDetail: false,
      GoodsPurchaseDetailList:[],

      // 备注时间范围
      daterangePurchaseDate: [],
      rangeArray : [null, null],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        purchaseDate: null,
        purchaseSn: null,
        purchaseTotal: null,
        purchaseState: null,
        supplierName: null

      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
    "goodsSkuInfoList":{
      handler(){
        this.form.purchaseTotal = 0;
        this.goodsSkuInfoList.forEach( item => {
          this.form.purchaseTotal += item.purchaseDetailCount * item.purchaseDetailPrice
        })
      }
      ,deep:true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    showDetail(row){
      this.titleDetail = row.purchaseSn + "明细"
      this.openDetail = true
      getGoodsSkuInfoByPurchaseId( row.purchaseId ).then(response => {
        this.GoodsPurchaseDetailList = response.data;
      });

    },

    /** 提交按钮 */
    submitFormAll() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.goodsPurchaseDetailList = this.goodsSkuInfoList
          if (this.form.purchaseId != null) {

            updateGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openAll = false;
              this.getList();
            });
          } else {
            addGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openAll = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdateAndGoodsSku(row) {
      this.reset();
      const purchaseId = row.purchaseId
      getGoodsPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.openAll = true;
        this.titleAll = "修改采购订单All";
      });
      getGoodsSkuInfoByPurchaseId( purchaseId ).then(response => {
        this.goodsSkuInfoList = response.data;
      });
    },

    handleDeleteGoodsSku(row){
      // console.log( row )
      // console.log( this.goodsSkuInfoList )
      // 使用indexOf查找对象位置
      let indexToRemove = this.goodsSkuInfoList.findIndex(item => item.skuId === row.skuId);
      if (indexToRemove !== -1) {
        this.goodsSkuInfoList.splice(indexToRemove, 1);
      }

      this.form.purchaseTotal = 0;
      this.goodsSkuInfoList.forEach( item => {
        this.form.purchaseTotal += item.purchaseDetailCount * item.purchaseDetailPrice
      })
    },

    selectSkuList(skuList){
      // console.log( skuList )
      skuList.forEach( item => {
        this.goodsSkuInfoList.push({
          skuId : item.skuId,
          purchaseDetailCount : 1 ,
          purchaseDetailPrice : item.skuPrice ,
          goodsName : item.goodsName,
          skuTitle : item.skuTitle

        } )
      })

      this.form.purchaseTotal = 0;
      this.goodsSkuInfoList.forEach( item => {
        this.form.purchaseTotal += item.purchaseDetailCount * item.purchaseDetailPrice
      })

    },

    handleAddAll(){
      this.reset();
      this.openAll = true;
      this.titleAll = "添加采购订单All";
      this.goodsSkuInfoList = []
    },

    openGoodsSkuPage(){
      // console.log( this.form.supplierId )
      if( this.form.supplierId == null ){
        this.$message({
          message: '请选择供应商',
          type: 'warning'
        })
        return;
      }
      this.openSelectSku = true;
      this.$nextTick(() => {
        let skuids = []
        if( this.goodsSkuInfoList!=null && this.goodsSkuInfoList.length > 0 ){
          skuids = this.goodsSkuInfoList.map(item => item.skuId);
        }

        this.$refs.GoodsSkuModal.init( this.form.supplierId, skuids );
      });
    },

    selectSupplier({ supplierId,  supplierName }){
      // console.log( supplierId,  supplierName)

      this.form.supplierName = supplierName
      this.form.supplierId = supplierId
      this.form.purchaseTotal = 0.0
    },

    openSupplierPage(){
      if( this.goodsSkuInfoList !=null && this.goodsSkuInfoList.length > 0){

        this.$confirm('是否要重新选择供应商？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.goodsSkuInfoList = []
          this.openSelectSupplier = true;
          this.$nextTick(() => {
            this.$refs.SupplierModal.init();
          });
        }).catch(() => {

        });

      }else{
        this.openSelectSupplier = true;
        this.$nextTick(() => {
          this.$refs.SupplierModal.init();
        });
      }
    },

    /** 查询采购订单列表 */
    getList() {

      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangePurchaseDate && '' != this.daterangePurchaseDate) {
        this.queryParams.params["beginPurchaseDate"] = this.daterangePurchaseDate[0];
        this.queryParams.params["endPurchaseDate"] = this.daterangePurchaseDate[1];
      }

      if (null != this.rangeArray && '' != this.rangeArray) {
        this.queryParams.params["beginPurchaseTotal"] = this.rangeArray[0];
        this.queryParams.params["endPurchaseTotal"] = this.rangeArray[1];
      }

      listGoodsPurchase(this.queryParams).then(response => {
        this.GoodsPurchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        supplierId: null,
        supplierName:null,
        purchaseDate: new Date(),
        purchaseSn: null,
        purchaseInfo: null,
        purchaseTotal: 0.0,
        purchaseState: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePurchaseDate = [];
      this.rangeArray = [null, null]
      this.queryParams.params = {};
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
    },




    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseId = row.purchaseId || this.ids
      getGoodsPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updateGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + purchaseIds + '"的数据项？').then(function() {
        return delGoodsPurchase(purchaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('webshop/GoodsPurchase/export', {
        ...this.queryParams
      }, `GoodsPurchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
